﻿using Ccteg.Common;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Ccteg.JobHostQuartz
{
    public class TaskWork
    {
        //定义全局变量 启动或停止执行任务
        private IScheduler _scheduler;

        public async void RunNewTaskById(Schedule schedule,     IServiceProvider _serviceProvider)
        {
            string res = "";
            try
            {
                //调度器工厂
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();//内存调度
                _scheduler = await schedulerFactory.GetScheduler();
                await _scheduler.GetJobGroupNames();
                //计划任务代码实现
                string taskName = schedule.JOBNAME;//任务名称
                string taskTime = schedule.TRIGGERDATECRON;//触发时间cron
                if (await _scheduler.CheckExists(new JobKey(taskName)))
                    await _scheduler.DeleteJob(new JobKey(taskName));
                IJobDetail jobDetail = new JobDetailImpl(taskName, typeof(WorkService));//AutoCount触发任务
                jobDetail.JobDataMap.Add("jobType", string.Format("{0}", schedule.JobType));
                jobDetail.JobDataMap.Add("IServiceProvider", _serviceProvider);
                 
        //ITrigger trigger = TriggerBuilder.Create().StartNow().WithCronSchedule(taskTime).Build();//创建触发时间
        ITrigger trigger = TriggerBuilder.Create().StartNow().WithSimpleSchedule(t =>
                t.WithIntervalInMinutes(150)
                 .RepeatForever()).Build();//创建触发时间.
                await _scheduler.ScheduleJob(jobDetail, trigger);//添加任务
                await _scheduler.Start();//启动
                //string msgEmail =
                //        string.Format("启动时间：{0}\n\t 启动任务名称：{1}\n\t 触发时间：{2}\n\t 触发地址：{3}\n\t 站点IP地址：{4}\n\t",
                //            DateTime.Now, taskName, taskTime, schedule.TRIGGERJOBURL, IpHelper.GetUserIp());
                //EmailManager.sendEmail(title + "任务调度启动邮件", msgEmail);
                res = "任务启动成功";

            }
            catch (Exception ex)
            {
                res = "任务启动异常";
                //发送邮件
                //string loginfo = string.Format("错误：{0}\n IP：{1}\n 结果：{2} \n ", ex.Message, IpHelper.GetUserIp(),
                //    string.Format("{0}:{1}({2})", res, jobName, schedule.ID));
                //EmailManager.sendEmail(title + "任务调度启动邮件", ex, string.Format("{0}:{1}({2})", res, jobName, schedule.ID), loginfo);
            }
        }
        /// <summary>
        /// 任务停止
        /// </summary>
        /// <param name="jobId">任务ID</param>
        /// <returns>任务执行结果</returns>
        public async void StopTaskById(Schedule schedule)
        {
            string res = "";
            string jobName = "";
            try
            {

                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();//内存调度
                _scheduler = await schedulerFactory.GetScheduler();
                jobName = schedule.JOBNAME;
                string taskName = schedule.JOBNAME;//任务名称
                if (await _scheduler.CheckExists(new JobKey(taskName)))
                    await _scheduler.DeleteJob(new JobKey(taskName));
                res = "任务停止成功";
                //string msgEmail =
                //      string.Format("结束时间：{0}\n\t 停止任务名称：{1}\n\t 触发时间：{2}\n\t 触发地址：{3}\n\t 站点IP地址：{4}\n\t",
                //          DateTime.Now, taskName, schedule.TRIGGERDATECRON, schedule.TRIGGERJOBURL, IpHelper.GetUserIp());
                //EmailManager.sendEmail(title + "任务调度停止邮件", msgEmail);

            }
            catch (Exception ex)
            {
                res = "任务停止异常";
                //发送邮件
                //string loginfo = string.Format("错误：{0}\n IP：{1}\n 结果：{2} \n ", ex.Message, IpHelper.GetUserIp(),
                //    string.Format("{0}:{1}({2})", res, jobName, schedule.ID));
                //EmailManager.sendEmail(title + "任务调度停止邮件", ex, string.Format("{0}:{1}({2})", res, jobName, schedule.ID), loginfo);

            }
        }
    }
}
